package net.ib.mtalk.network.task;

import android.content.Context;
import android.os.Handler;
import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.AddBuddyReq;
import net.ib.mntalk.protocol.Session.AddBuddyRes;
import net.ib.mntalk.protocol.Session.AddContactsReq;
import net.ib.mntalk.protocol.Session.AddContactsRes;
import net.ib.mntalk.protocol.Session.GetSuggestionsRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.helper.SuggestionDatabaseHelper;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.util.MTalkLogWriter;

public class InsertBuddyTask extends AsyncNetTask {
	
	private AddBuddyReq mAddBuddyReq;
	
	public InsertBuddyTask(Context context, Handler uiHandler, AddBuddyReq addBuddyReq) {
		super(context, uiHandler);
		this.mAddBuddyReq = addBuddyReq;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mAddBuddyReq)
			.setMethodId(Session.Contact.AddBuddy)	// TODO
			.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject,	Object receivedObject) {
		MTalkLogWriter.d("InsertBuddyTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		AddBuddyRes addBuddyRes = (AddBuddyRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("InsertBuddyTask ResponseCode : " + addBuddyRes.getResponseCode());
		
		if(addBuddyRes.getResponseCode() == Common.SUCCESS){
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ADD_BUDDY_SUCCESS));
			SuggestionDatabaseHelper.deleteSuggestion(mContext, mAddBuddyReq);
		} else if(addBuddyRes.getResponseCode() == Common.NOT_EXIST_OBJECT){
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ADD_BUDDY_DELETED));
			SuggestionDatabaseHelper.deleteSuggestion(mContext, mAddBuddyReq);
		} else if(addBuddyRes.getResponseCode() == Common.ALREADY_CACHED_OBJECT){
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ALREADY_FRIEND));
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_ADD_BUDDY_FAIL));
		}
	}

}
